using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Design;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using System.Workflow.Activities;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Serialization;
using System.Xml;
using OpenComposite.Base;
using OpenComposite.Base.Collections;
using OpenComposite.Base.Designer;
using OpenComposite.Repository.TFS;
using OpenComposite.Workflow.Extenders;
using OpenComposite.EII.CodeGenerators;
using OpenComposite.EII.Designer.BUSView;
using OpenComposite.EII.Designer.SCA;
using OpenComposite.EII.Designer.Workflow.Forms;
using OpenComposite.EII.Forms;
using OpenComposite.EII.Interfaces;
using OpenComposite.EII.Repository;
using OpenComposite.EII.Services;
using OpenComposite.EII.Simulation;
using OpenComposite.Workflow;
using OpenComposite.Workflow.Interfaces;
using WeifenLuo.WinFormsUI.Docking;

namespace OpenComposite.EII.Designer.Workflow
{
	/// <summary>
	/// The main form for the design, configuration and genetation of a workflow
	/// (orchestration/composite or business process/composite application).
	/// </summary>
	public partial class FormWorkflowDesigner : DockContent
	{
		#region Initialization
		/// <summary>
		/// Initialize a new instance of the FormWorkflowDesigner class.
		/// </summary>
		public FormWorkflowDesigner()
		{
			InitializeComponent();

			init();
		}
		/// <summary>
		/// Initialize a new instance of the FormWorkflowDesigner class.
		/// </summary>
		/// <param name="wfcontroller"></param>
		public FormWorkflowDesigner(WorkflowController wfcontroller)
		{
			_wfcontroller = wfcontroller;

			_wfcontroller.Loaded += new EventHandler(_wfcontroller_Loaded);
			_wfcontroller.Closing += new CancelEventHandler(_wfcontroller_Closing);

			_dicNameController.Add(cOrchestration, _wfcontroller);

			_wfToolboxCategory = _wfcontroller.ToolboxCategory;

			InitializeComponent();

			init();

		}

		void Workflow_ItemDeleted(object sender, RepositoryEventArgs e)
		{
			this.Close();
		}

		private void init()
		{
			Bitmap bmp = btnDeployOptions.Image as Bitmap;
			if ( bmp != null ) {
				bmp.MakeTransparent();
			}
			Repository.RepositoryChanged += new RepositoryChangedEventHandler(Repository_RepositoryChanged);
		}
		#endregion

		#region Public Members

		#region Properties
		/// <summary>
		/// Gets the workflow view tabpage.
		/// </summary>
		public TabPage WorkflowViewTab
		{
			get { return tabWorkflow; }
		}
		/// <summary>
		/// Gets the process flow policy tabpage.
		/// </summary>
		public TabPage ProcessFlowPolicyTab
		{
			get { return tabProcFlowPolicy; }
		}
		/// <summary>
		/// Gets the participant policy tabpage.
		/// </summary>
		public TabPage ParticipantPolicyTab
		{
			get { return tabParticipantPolicy; }
		}
		/// <summary>
		/// Gets the binding tabpage.
		/// </summary>
		public TabPage BindingTab
		{
			get { return tabBinding; }
		}
		/// <summary>
		/// Gets the subscriptions tabpage.
		/// </summary>
		public TabPage SubscriptionTab
		{
			get { return tabSubscriptions; }
		}
		/// <summary>
		/// Gets the composite view tabpage.
		/// </summary>
		public TabPage CompositeViewTab
		{
			get { return tabComposite; }
		}
		/// <summary>
		/// Gets the deploy/generate tabpage.
		/// </summary>
		public TabPage DeployTab
		{
			get { return tabDeploy; }
		}

		public RepositorySurface ActiveSurface
		{
			get;
			protected set;
		}
		#endregion

		#endregion

		#region Protected Members

		#region Properties
		/// <summary>
		/// Gets the repository service.
		/// </summary>
		protected RepositoryService Repository
		{
			get { return (RepositoryService)_wfcontroller.GetService(typeof(RepositoryService)); }
		}
		#endregion

		#endregion

		#region Internal Members

		internal OpenComposite.EII.Repository.Workflow Workflow
		{
			get { return this._wfcontroller.Workflow; }
		}

		#endregion

		#region Private Members

		#region Constants
		private const string cOrchestration = "Orchestration";
		private const string cFlowPolicy = "Flow Policy";
		private const string cParticipantPolicy = "Participant Policy";
		private const string cSubscriptions = "Subscriptions";
		private const string cComposite = "Composite";
		#endregion

		#region Variables
		private bool _isWValidatorInitialized = false;
		private bool _isLoading = false;
		private string _wfToolboxCategory;

		private WorkflowController _wfcontroller = null;
		private UCBinding _ucBinding = null;
		private Dictionary<string, IController> _dicNameController = new Dictionary<string, IController>();
		private MainToolboxService _toolBoxService = null;
		#endregion

		#region Methods
		private void doDeploy(bool update)
		{
			_wfcontroller.Workflow.ExtendedProperties.DeployingCounter++;

			string path = txtTargetFolder.Text;
			if ( string.IsNullOrEmpty(path) || !Directory.Exists(path) ) {
				dlgSelectFolder.SelectedPath = path;
				if ( !dlgSelectFolder.SelectedPath.EndsWith("\\") )
					dlgSelectFolder.SelectedPath += "\\";
				if ( dlgSelectFolder.ShowDialog() == DialogResult.OK ) {
					txtTargetFolder.Text = dlgSelectFolder.SelectedPath;
				} else {
					return;
				}
			}

			string serverPath = _wfcontroller.Workflow.ExtendedProperties.SourceControlPath;
			string localPath = txtTargetFolder.Text;
			_wfcontroller.DeployVSProjectCSharp(txtTargetFolder.Text, update);
			if ( _wfcontroller.Workflow.ExtendedProperties.ConnectWithSourceControlOnDeploy ) {
				if ( !string.IsNullOrEmpty(serverPath) ) {
					if ( !serverPath.EndsWith(_wfcontroller.Workflow.Name) &&
						!serverPath.EndsWith("/" + _wfcontroller.Workflow.Name) ) {
						serverPath += ( serverPath.EndsWith("/") ? "" : "/" ) + _wfcontroller.Workflow.Name;
					}
					try {
						TeamFoundationWrapper.ConnectAndCheckIntoTfs(_wfcontroller, serverPath, localPath);
					} catch ( Exception ex ) {
						Debug.WriteLine(ex.ToString());
					}
				}
			}
		}

		private void doSimulation()
		{
			using ( new WaitMouse() ) {
				FormWorkflowSimulation frmSim = null;
				List<FormWorkflowSimulation> forms = DockPanel.FindChildForms<FormWorkflowSimulation>();
				foreach ( FormWorkflowSimulation form in forms ) {
					if ( form.WorkflowController == _wfcontroller ) {
						frmSim = form;
						break;
					}
				}
				if ( frmSim == null ) {
					this.Refresh();
					_wfcontroller.Save();
					frmSim = new FormWorkflowSimulation(_wfcontroller);
					frmSim.Show(DockPanel);
					frmSim.BringToFront();
				} else {
					frmSim.Show();
					frmSim.BringToFront();
				}
			}
		}
		private void showBUSView()
		{
			#region TIMER
#if TIMER
			Debug.WriteLine("-----ShowBUSView-----");
			Debug.WriteLine("doCreateComposite: " + DateTime.Now.ToString("HH:mm:ss.fffffff"));
#endif
			#endregion

			if ( string.IsNullOrEmpty(_wfcontroller.Workflow.StartName) ) {
				doCreateComposite(true);
			}

			#region TIMER
#if TIMER
			Debug.WriteLine("busCtrler: " + DateTime.Now.ToString("HH:mm:ss.fffffff"));
#endif
			#endregion

			int loopcounter = 0;
			RepositoryService repSvc = this.Repository;
			BUSView.BUSViewController busCtrler;
			if ( _dicNameController.ContainsKey(cSubscriptions) ) {
				busCtrler = (BUSView.BUSViewController)_dicNameController[cSubscriptions];
			} else {
				busCtrler = this.Repository.CreateDesignController(this.DockPanel, ItemType.BUS) as BUSView.BUSViewController;
				busCtrler.WorkflowServiceProvider = _wfcontroller;
				busCtrler.Load(_wfcontroller.Workflow, Global.Status.CurrentRepositoryId, Global.Status.CurrentDomainId);
				_dicNameController.Add(cSubscriptions, busCtrler);
			}
			busCtrler.RefreshSwitchButtons();
			#region TIMER
#if TIMER
			Debug.WriteLine("SearchBusSymbol: " + DateTime.Now.ToString("HH:mm:ss.fffffff"));
#endif
			#endregion
SearchBusSymbol:
			UserControl view = busCtrler.GetView(ViewTechnology.Default) as UserControl;//.DesignerDockContent.DesignerView;
			BUSSymbol bus = null;
			BUSVariablesSymbol vars = null;
			foreach ( DesignerControl dc in busCtrler.DesignerView.DesignerControls ) {
				if ( dc is BUSSymbol ) {
					bus = (BUSSymbol)dc;
					if ( vars != null ) break;
				} else if ( dc is BUSVariablesSymbol ) {
					vars = (BUSVariablesSymbol)dc;
					if ( bus != null ) break;
				}
			}
			#region TIMER
#if TIMER
			Debug.WriteLine("busCtrler.Load: " + DateTime.Now.ToString("HH:mm:ss.fffffff"));
#endif
			#endregion
			if ( bus == null ) {
				if ( busCtrler != null ) {
					busCtrler.WorkflowServiceProvider = _wfcontroller;
					busCtrler.Load(_wfcontroller.Workflow, Global.Status.CurrentRepositoryId, Global.Status.CurrentDomainId);
					loopcounter++;
					if ( loopcounter > 1 ) {
						_wfcontroller.Workflow.BUSDiagram = null;
						showBUSView();
						return;
					}
					goto SearchBusSymbol;
				} else {
					_wfcontroller.Workflow.BUSDiagram = null;
					showBUSView();
					return;
				}
			}
			#region TIMER
#if TIMER
			Debug.WriteLine("lstExistingSymbols: " + DateTime.Now.ToString("HH:mm:ss.fffffff"));
#endif
			#endregion

			int iTopMaxX = bus.ActivitiesMinX, iBottomMaxX = bus.ActivitiesMinX;
			List<BUSActivitySymbol> lstExistingSymbols = new List<BUSActivitySymbol>();

			CompositeActivity rootAct = this.Workflow.GetRootActivity() as CompositeActivity;
			List<Activity> activities = rootAct.GetNestedActivities();

			foreach ( DesignerControl dc in busCtrler.DesignerView.DesignerControls ) {
				BUSActivitySymbol bas = dc as BUSActivitySymbol;
				if ( bas != null ) {
					lstExistingSymbols.Add(bas);
					if ( dc.Bottom < bus.Top ) {
						if ( dc.Right > iTopMaxX ) iTopMaxX = dc.Right;
					} else {
						if ( dc.Right > iBottomMaxX ) iBottomMaxX = dc.Right;
					}
					ITextActivity act =
						Helpers.GetActivityByLogicalActivityID(activities, bas.LogicalActivity.ID) as ITextActivity;
					if ( act != null && !string.IsNullOrEmpty(act.Text) ) {
						bas.Text = act.Text;
					}
				}
			}
			bus.Width = ( iTopMaxX > iBottomMaxX ? iTopMaxX : iBottomMaxX ) - bus.Left;
			if ( bus.Right > busCtrler.DesignerPanel.Width ) {
				bus.Width = busCtrler.DesignerPanel.Width - bus.Left;
			}
			#region TIMER
#if TIMER
			Debug.WriteLine("BUS Variable Symbol: " + DateTime.Now.ToString("HH:mm:ss.fffffff"));
#endif
			#endregion

			// BUS Variable Symbol
			if ( vars == null ) {
				vars = repSvc.CreateDesignerControl(ItemType.BUSVariables, false) as BUSVariablesSymbol;
				vars.Location = new Point(bus.Left, bus.Bottom + 20);
				busCtrler.DesignerView.DesignerControls.Add(vars);
			}
			if ( vars != null ) {
				foreach ( WorkflowField wf in _wfcontroller.Workflow.Interface.Fields ) {
					BusinessObject bo = wf.GetContainerBusinessObject();
					if ( bo == null ) {
						wf.CreateContainerBusinessObject();
						bo = wf.GetContainerBusinessObject();
					}
					if ( bo != null && !vars.NamedBusinessObjects.Contains(bo) ) {
						vars.NamedBusinessObjects.Add(bo.Name, bo, null);
					}
				}
			}

			#region TIMER
#if TIMER
			Debug.WriteLine("getLogicalActivities: " + DateTime.Now.ToString("HH:mm:ss.fffffff"));
#endif
			#endregion

			List<OpenComposite.Workflow.LogicalCapabilityActivity> logcaps;
			List<OpenComposite.Workflow.LogicalInputActivity> loginActs;
			List<OpenComposite.Workflow.LogicalMethodCallActivity> logmeths;
			List<OpenComposite.Workflow.DataAggregatorActivity> dataaggrs;
			List<OpenComposite.Workflow.RuleEvaluatorActivity> reas;
			List<OpenComposite.Workflow.NotificationActivity> notiacts;

			getLogicalActivities(out logcaps, out loginActs, out logmeths, out dataaggrs, out reas, out notiacts);

			#region TIMER
#if TIMER
			Debug.WriteLine("add capability symbols: " + DateTime.Now.ToString("HH:mm:ss.fffffff"));
#endif
			#endregion

			// add capability symbols
			foreach ( LogicalCapabilityActivity logcap in logcaps ) {
				LogicalActivity logact = repSvc.GetItem<LogicalActivity>(logcap.LogicalActivityId);
				if ( logact == null ) continue;
				bool changed = false;
				if ( logact.DisplayName != logcap.Text ) {
					logact.DisplayName = logcap.Text;
					changed = true;
				}
				if ( logact.Name != logcap.Name ) {
					logact.Name = logcap.Name;
					changed = true;
				}
				string newVarName = logcap.GetValue(OutputVariableNameExtenderProvider.OutputVarNameProperty) as string;
				if ( logact.HasOutputBusinessObject && logact.OutputVariableName != newVarName ) {
					logact.OutputVariableName = newVarName;
					changed = true;
				}
				if ( changed ) logact.Save();
				BUSActivitySymbol bas = addBUSActivity(logact, busCtrler.DesignerView, bus, ref iTopMaxX, ref iBottomMaxX);
				if ( lstExistingSymbols.Contains(bas) ) {
					lstExistingSymbols.Remove(bas);
				}
			}
			//}

			#region TIMER
#if TIMER
			Debug.WriteLine("add Logical Input Activities: " + DateTime.Now.ToString("HH:mm:ss.fffffff"));
#endif
			#endregion

			// add Logical Input Activities
			bus.InputBusinessObjects.Clear();
			foreach ( var loginact in loginActs ) {
				LogicalActivity logact = repSvc.GetItem<LogicalActivity>(loginact.LogicalActivityId);
				if ( logact == null ) continue;
				WorkflowEvent we = logact.GetWorkflowEvent();
				if ( we == null ) continue;
				bool changed = false;
				if ( logact.DisplayName != loginact.Text ) {
					logact.DisplayName = loginact.Text;
					changed = true;
				}
				if ( we.IsStart && we.BusinessObject != null ) {
					string newVarName = loginact.GetValue(OutputVariableNameExtenderProvider.OutputVarNameProperty) as string;
					if ( logact.HasOutputBusinessObject && logact.OutputVariableName != newVarName ) {
						logact.OutputVariableName = newVarName;
						changed = true;
					}
					//if ( !bus.InputBusinessObjects.Contains(we.BusinessObject) ) {
					bus.InputBusinessObjects.Add(logact.OutputVariableName, we.BusinessObject, logact);
					//}
				} else if ( we.BusinessObject != null ) {
					if ( logact.Name != loginact.Name ) {
						logact.Name = loginact.Name;
						changed = true;
					}
					BUSActivitySymbol bas = addBUSActivity(logact, busCtrler.DesignerView, bus, ref iTopMaxX, ref iBottomMaxX);
					if ( lstExistingSymbols.Contains(bas) ) {
						lstExistingSymbols.Remove(bas);
					}
				}
				if ( changed ) logact.Save();
			}
			#region TIMER
#if TIMER
			Debug.WriteLine("add Logical Method Call Activities: " + DateTime.Now.ToString("HH:mm:ss.fffffff"));
#endif
			#endregion

			// add Logical Method Call Activities
			foreach ( var logmeth in logmeths ) {
				LogicalActivity logact = repSvc.GetItem<LogicalActivity>(logmeth.LogicalActivityId);
				if ( logact == null ) continue;
				WorkflowMethod wm = logact.GetWorkflowMethod();
				if ( wm != null &&
					 ( wm.OutputBusinessObject != null || wm.InputBusinessObject != null ) ) {
					if ( logact.Name != logmeth.Name ) {
						logact.Name = logmeth.Name;
						logact.Save();
					}
					BUSActivitySymbol bas = addBUSActivity(logact, busCtrler.DesignerView, bus, ref iTopMaxX, ref iBottomMaxX);
					if ( lstExistingSymbols.Contains(bas) ) {
						lstExistingSymbols.Remove(bas);
					}
					bas.IsProcessReply = logmeth == logmeths[logmeths.Count - 1];
					if ( bas.IsProcessReply ) {
						bas.Location = new Point(bus.Location.X, bus.Location.Y + 20);
						bus.HasOutput = true;
					}
				}
				bool changed = false;
				if ( logact.DisplayName != logmeth.Text ) {
					logact.DisplayName = logmeth.Text;
					changed = true;
				}
				if ( changed ) logact.Save();
			}
			#region TIMER
#if TIMER
			Debug.WriteLine("add Data Aggregators: " + DateTime.Now.ToString("HH:mm:ss.fffffff"));
#endif
			#endregion

			// add Data Aggregators
			foreach ( OpenComposite.Workflow.DataAggregatorActivity daa in dataaggrs ) {
				LogicalActivity logact = repSvc.GetItem<LogicalActivity>(daa.LogicalActivityId);
				if ( logact == null ) continue;
				bool changed = false;
				if ( logact.Name != daa.Name ) {
					logact.Name = daa.Name;
					changed = true;
				}
				if ( logact.DisplayName != daa.Text ) {
					logact.DisplayName = daa.Text;
					changed = true;
				}
				string newVarName = daa.GetValue(OutputVariableNameExtenderProvider.OutputVarNameProperty) as string;
				if ( logact.OutputVariableName != newVarName ) {
					logact.OutputVariableName = newVarName;
					changed = true;
				}
				if ( changed ) logact.Save();
				BUSActivitySymbol bas = addBUSActivity(logact, busCtrler.DesignerView, bus, ref iTopMaxX, ref iBottomMaxX);
				if ( lstExistingSymbols.Contains(bas) ) {
					lstExistingSymbols.Remove(bas);
				}
			}

			#region TIMER
#if TIMER
			Debug.WriteLine("add Rule Evaluators: " + DateTime.Now.ToString("HH:mm:ss.fffffff"));
#endif
			#endregion

			// add Rule Evaluators
			foreach ( OpenComposite.Workflow.RuleEvaluatorActivity rea in reas ) {
				LogicalActivity logact = repSvc.GetItem<LogicalActivity>(rea.LogicalActivityId);
				if ( logact == null ) continue;
				bool changed = false;
				if ( logact.Name != rea.Name ) {
					logact.Name = rea.Name;
					changed = true;
				}
				if ( logact.DisplayName != rea.Text ) {
					logact.DisplayName = rea.Text;
					changed = true;
				}
				string newVarName = rea.GetValue(OutputVariableNameExtenderProvider.OutputVarNameProperty) as string;
				if ( logact.HasOutputBusinessObject && logact.OutputVariableName != newVarName ) {
					logact.OutputVariableName = newVarName;
					changed = true;
				}
				if ( changed ) logact.Save();
				BUSActivitySymbol bas = addBUSActivity(logact, busCtrler.DesignerView, bus, ref iTopMaxX, ref iBottomMaxX);
				if ( lstExistingSymbols.Contains(bas) ) {
					lstExistingSymbols.Remove(bas);
				}
			}
			// add Notifications
			foreach ( OpenComposite.Workflow.NotificationActivity notiact in notiacts ) {
				LogicalActivity logact = repSvc.GetItem<LogicalActivity>(notiact.LogicalActivityId);
				bool changed = false;
				if ( logact == null ) {
					IRepositoryItem parentItem = null;
					logact = repSvc.GetNewItem<LogicalActivity>(false, ref parentItem);
					logact.Name = notiact.Name;
					logact.LogicalActivityType = LogicalActivityType.Notification;
					changed = true;
					notiact.LogicalActivityId = logact.ID;
				} else if ( logact.Name != notiact.Name ) {
					logact.Name = notiact.Name;
					changed = true;
				}
				if ( logact.DisplayName != notiact.Text ) {
					logact.DisplayName = notiact.Text;
					changed = true;
				}
				if ( changed ) logact.Save();
				BUSActivitySymbol bas = addBUSActivity(logact, busCtrler.DesignerView, bus, ref iTopMaxX, ref iBottomMaxX);
				if ( lstExistingSymbols.Contains(bas) ) {
					lstExistingSymbols.Remove(bas);
				}
			}
			//Cursor.Current = Cursors.Default;

			#region TIMER
#if TIMER
			Debug.WriteLine("tabSubscriptions.Controls.Add(view): " + DateTime.Now.ToString("HH:mm:ss.fffffff"));
#endif
			#endregion

			if ( !tabSubscriptions.Controls.Contains(view) ) {
				view.Dock = DockStyle.Fill;
				tabSubscriptions.Controls.Add(view);
			}

			#region TIMER
#if TIMER
			Debug.WriteLine("bas.Remove();: " + DateTime.Now.ToString("HH:mm:ss.fffffff"));
#endif
			#endregion

			foreach ( BUSActivitySymbol bas in lstExistingSymbols ) {
				bas.Remove();
			}

			//this.ResumeLayout(true);
			//this.Refresh();

			//busCtrler.Show(this.DockPanel);
			#region TIMER
#if TIMER
			Debug.WriteLine("Update: " + DateTime.Now.ToString("HH:mm:ss.fffffff"));
#endif
			#endregion

			busCtrler.Update();
		}

		private void showProcessPolicy()
		{
			BusinessPolicy procPolicy = _wfcontroller.Workflow.ProcessPolicy;
			DesignController ctrler;
			if ( !_dicNameController.ContainsKey(cFlowPolicy) ) {
				ctrler = this.Repository.CreateDesignController(this.DockPanel, procPolicy, Global.Status.CurrentRepositoryId) as DesignController;
				if ( ctrler == null ) {
					MessageBox.Show("RepositoryFactory.CreateDesignController failed.");
					return;
				}
				IMainController mainCtrler = _wfcontroller.GetService(typeof(IMainController)) as IMainController;
				if ( mainCtrler != null ) {
					mainCtrler.RegisterControllerEvents(ctrler);
				}
				//ctrler.Show(this.DockPanel);
				Control c = ctrler.GetView(ViewTechnology.Default) as Control;
				if ( !tabProcFlowPolicy.Contains(c) ) {
					c.Dock = DockStyle.Fill;
					tabProcFlowPolicy.Controls.Add(c);
				}
				_dicNameController.Add(cFlowPolicy, ctrler);
				//ctrler.ToolboxDockContent.ShowHint = DockState.DockRightAutoHide;
				//OpenComposite.EII.Services.MainToolboxService mts =
				//    _wfcontroller.GetService(typeof(System.Drawing.Design.IToolboxService)) as OpenComposite.EII.Services.MainToolboxService;
				//if ( mts != null ) {
				//    ctrler.Toolbox.Show(mts.Pane, _wfcontroller.ToolboxForm);
				//} else {
				//    ctrler.Toolbox.Show(_wfcontroller.ToolboxForm.Pane, _wfcontroller.ToolboxForm);
				//}
			} else {
				//ctrler = (DesignController)_dicNameController[cFlowPolicy];
				//ctrler.Toolbox.Show();
				//ctrler.Toolbox.Refresh();
			}
		}
		private void showParticipantPolicy()
		{
			BusinessPolicy partPolicy = _wfcontroller.Workflow.ParticipantPolicy;
			DesignController ctrler;
			if ( !_dicNameController.ContainsKey(cParticipantPolicy) ) {
				ctrler = this.Repository.CreateDesignController(this.DockPanel, partPolicy, Global.Status.CurrentRepositoryId) as DesignController;
				if ( ctrler == null ) {
					MessageBox.Show("RepositoryFactory.CreateDesignController failed.");
					return;
				}
				IMainController mainCtrler = _wfcontroller.GetService(typeof(IMainController)) as IMainController;
				if ( mainCtrler != null ) {
					mainCtrler.RegisterControllerEvents(ctrler);
				}
				//ctrler.Show(this.DockPanel);
				Control c = ctrler.GetView(ViewTechnology.Default) as Control;
				Debug.Assert(c != null);
				if ( !tabParticipantPolicy.Contains(c) ) {
					c.Dock = DockStyle.Fill;
					tabParticipantPolicy.Controls.Add(c);
				}
				_dicNameController.Add(cParticipantPolicy, ctrler);
				//ctrler.Toolbox.Show(_wfcontroller.ToolboxForm.Pane, _wfcontroller.ToolboxForm);
			} else {
				//ctrler = (DesignController)_dicNameController[cParticipantPolicy];
				//ctrler.Toolbox.Show();
				//ctrler.Toolbox.Refresh();
			}
		}
		private void showBindingMapping()
		{
			FormBindingMapping frm = new FormBindingMapping(this._wfcontroller);
			frm.Show(this.DockPanel);
		}
		private void showBinding()
		{
			//using ( new WaitMouse() ) {
			//    _wfcontroller.Save();
			//}
			if ( _ucBinding == null ) {
				_ucBinding = new UCBinding(this._wfcontroller);
			}
			if ( !tabBinding.Contains(_ucBinding) ) {
				_ucBinding.Dock = DockStyle.Fill;
				tabBinding.Controls.Add(_ucBinding);
				_ucBinding.Activate();
			} else {
				_ucBinding.Activate();
			}
		}
		private void doCreateSOBA()
		{
			RepositoryService repSvc = (RepositoryService)_wfcontroller.GetService(typeof(RepositoryService));
			if ( repSvc == null )
				throw new NullReferenceException("RepositoryService not available.");

			bool sc;
			bool isNew = false;
			_wfcontroller.Save();
			List<OpenComposite.Workflow.LogicalCapabilityActivity> lstLogActs = getLogicalCapabilityActivities();
			SOBA soba = _wfcontroller.Workflow.GetSOBA();

			if ( soba == null ) {
				if ( string.IsNullOrEmpty(_wfcontroller.Workflow.StartName) ) {
					if ( _wfcontroller.Workflow.BuildType == WorkflowBuildType.WCF_WindowsForm ) {
						//
						MessageBox.Show("Please add a Logical Input Event marked as 'Is Start' Event.", "Missing Start Event", MessageBoxButtons.OK, MessageBoxIcon.Warning);
						return;
					} else {
						// config start operation
						FormCreateProcess frm = new FormCreateProcess(_wfcontroller);
						frm.Text = "Define Process Start Operation";
						frm.ProcessName = "Start";
						frm.ProcessDescription = "This is the start operation of the business process.";
						if ( frm.ShowDialog() != DialogResult.OK ) {
							// cancel
							return;
						}
						_wfcontroller.Workflow.StartName = frm.ProcessName;
						_wfcontroller.Workflow.StartDescription = frm.ProcessDescription;
						_wfcontroller.Workflow.InputBusinessObject = frm.InputBusinessObject;
						_wfcontroller.Workflow.OutputBusinessObject = frm.OutputBusinessObject;
					}
				}
				soba = repSvc.GetItem(ItemType.SOBA, true, Global.Status.CurrentRepositoryId, false, false, out sc) as SOBA;
				if ( soba == null ) {
					MessageBox.Show("Failed to create SOBA.");
					return;
				}
				soba.WorkflowID = _wfcontroller.Workflow.ID;
				soba.Name = _wfcontroller.ClassName;
				soba.CreatedType = CreatedTypeFlags.RecursiveDeleteAllowed;
				soba.Save();
				Global.Data.AddRepositoryItemToDomainFolder(Global.Status.CurrentDomainId, soba);
				isNew = true;
			}
			DesignController ctrler = repSvc.CreateDesignController(this.DockPanel, soba, Global.Status.CurrentRepositoryId) as DesignController;
			if ( ctrler == null ) {
				MessageBox.Show("RepositoryFactory.CreateDesignController failed.");
				return;
			}
			IMainController mainCtrler = _wfcontroller.GetService(typeof(IMainController)) as IMainController;
			if ( mainCtrler != null ) {
				mainCtrler.RegisterControllerEvents(ctrler);
			}
			if ( isNew ) {
				#region Create New SOBA
				SOBASymbol ctrlMain = ctrler.DesignerDockContent.DesignerView.MainControl as SOBASymbol;
				if ( ctrlMain == null ) {
					MessageBox.Show("MainControl is not a SOBASymbol.");
					return;
				}
				// add orchestration component
				Service svcOrch = repSvc.GetItem(ItemType.OrchestrationComponent, true, Global.Status.CurrentRepositoryId, false, false, out sc) as Service;
				OrchestrationComponentSymbol osym = null;
				if ( svcOrch != null ) {
					svcOrch.Name = _wfcontroller.ClassName;
					svcOrch.CreatedType = CreatedTypeFlags.RecursiveDeleteAllowed;
					osym = repSvc.CreateDesignerControl(svcOrch) as OrchestrationComponentSymbol;
					if ( osym != null ) {
						osym.Location = new Point(100, 50);
						osym.ProcessOperation = repSvc.GetItem(ItemType.Operation, true, Global.Status.CurrentRepositoryId, false, false, out sc) as Operation;
						if ( osym.Interfaces.Count > 0 )
							osym.Interfaces[0].Operations.Add(osym.ProcessOperation);
						if ( osym.ProcessOperation != null ) {
							osym.ProcessOperation.Name = _wfcontroller.Workflow.StartName;
							osym.ProcessOperation.Description = _wfcontroller.Workflow.StartDescription;
							osym.ProcessOperation.SetInputBusinessObject(_wfcontroller.Workflow.InputBusinessObject);
							osym.ProcessOperation.SetOutputBusinessObject(_wfcontroller.Workflow.OutputBusinessObject);
							osym.ProcessOperation.WorkflowId = _wfcontroller.Workflow.ID;
						}
						ctrlMain.Controls.Add(osym);
						if ( ctrlMain.Interfaces.Count > 0 && osym.Interfaces.Count > 0 )
							ctrlMain.Interfaces[0].DropObject(osym.Interfaces[0], ctrlMain.Interfaces[0].Location, MouseButtons.Right);
					}
				}
				// add capability symbols
				for ( int i = 0; i < lstLogActs.Count; i++ ) {
					LogicalActivity lact = repSvc.GetItem(ItemType.LogicalActivity, lstLogActs[i].LogicalActivityId, false) as LogicalActivity;
					CapabilitySymbol csym = repSvc.CreateDesignerControl(lact) as CapabilitySymbol;
					if ( csym != null ) {
						csym.Location = new Point(300, 20 + ( i * 60 ));
						ctrlMain.Controls.Add(csym);
						if ( osym != null ) {
							if ( osym.References.Count == 0 )
								csym.DropObject(osym, csym.Location, MouseButtons.Right);
							else
								csym.DropObject(osym.References[0], csym.Location, MouseButtons.Right);
						}
					}
				}
				_wfcontroller.LoadWorkflow(_wfcontroller.Workflow);
				#endregion
			} else {
				#region Check Existing SOBA
				SOBASymbol ctrlMain = ctrler.DesignerDockContent.DesignerView.MainControl as SOBASymbol;
				if ( ctrlMain == null ) {
					MessageBox.Show("MainControl is not a SOBASymbol.");
					return;
				}
				int i = 0;
				OrchestrationComponentSymbol osym = null;
				List<CapabilitySymbol> lstDeletedCaps = new List<CapabilitySymbol>();
				List<OpenComposite.Workflow.LogicalCapabilityActivity> lstNewLogCaps =
					new List<OpenComposite.Workflow.LogicalCapabilityActivity>(lstLogActs);
				//int ypos = 0;
				foreach ( DesignerControl ctrl in ctrlMain.Controls ) {
					if ( ctrl is OrchestrationComponentSymbol && osym == null ) {
						osym = (OrchestrationComponentSymbol)ctrl;
						continue;
					}
					CapabilitySymbol csym = ctrl as CapabilitySymbol;
					if ( csym != null ) {
						bool exists = false;
						if ( csym.RepositoryItem != null ) {
							i++;
							foreach ( OpenComposite.Workflow.LogicalCapabilityActivity lgcap in lstLogActs ) {
								if ( lgcap.LogicalActivityId > 0 ) {
									LogicalActivity lact = repSvc.GetItem(ItemType.LogicalActivity, lgcap.LogicalActivityId, false) as LogicalActivity;
									if ( lact != null && lact.ID == csym.RepositoryItem.ID ) {
										exists = true;
										lstNewLogCaps.Remove(lgcap);
										break;
									}
								}
							}
						}
						if ( !exists ) {
							lstDeletedCaps.Add(csym);
						}
					}
				}
				foreach ( CapabilitySymbol csym in lstDeletedCaps ) {
					csym.Remove();
				}
				if ( osym == null ) {
					// add orchestration component
					Service svcOrch = repSvc.GetItem(ItemType.OrchestrationComponent, true, Global.Status.CurrentRepositoryId, false, false, out sc) as Service;
					if ( svcOrch != null ) {
						svcOrch.Name = _wfcontroller.ClassName;
						svcOrch.CreatedType = CreatedTypeFlags.RecursiveDeleteAllowed;
						osym = repSvc.CreateDesignerControl(svcOrch) as OrchestrationComponentSymbol;
						if ( osym != null ) {
							osym.Location = new Point(100, 50);
							osym.ProcessOperation = repSvc.GetItem(ItemType.Operation, true, Global.Status.CurrentRepositoryId, false, false, out sc) as Operation;
							if ( osym.Interfaces.Count > 0 )
								osym.Interfaces[0].Operations.Add(osym.ProcessOperation);
							if ( osym.ProcessOperation != null ) {
								osym.ProcessOperation.Name = _wfcontroller.Workflow.StartName;
								osym.ProcessOperation.Description = _wfcontroller.Workflow.StartDescription;
								osym.ProcessOperation.SetInputBusinessObject(_wfcontroller.Workflow.InputBusinessObject);
								osym.ProcessOperation.SetOutputBusinessObject(_wfcontroller.Workflow.OutputBusinessObject);
								osym.ProcessOperation.WorkflowId = _wfcontroller.Workflow.ID;
							}
							ctrlMain.Controls.Add(osym);
							if ( ctrlMain.Interfaces.Count > 0 && osym.Interfaces.Count > 0 )
								ctrlMain.Interfaces[0].DropObject(osym.Interfaces[0], ctrlMain.Interfaces[0].Location, MouseButtons.Right);
						}
					}
				}

				foreach ( OpenComposite.Workflow.LogicalCapabilityActivity logcap in lstNewLogCaps ) {
					LogicalActivity lact = repSvc.GetItem(ItemType.LogicalActivity, logcap.LogicalActivityId, false) as LogicalActivity;
					CapabilitySymbol csym = repSvc.CreateDesignerControl(lact) as CapabilitySymbol;
					if ( csym != null ) {
						csym.Location = new Point(300, 20 + ( i * 60 ));
						ctrlMain.Controls.Add(csym);
						if ( osym != null ) {
							if ( osym.References.Count == 0 )
								csym.DropObject(osym, csym.Location, MouseButtons.Right);
							else
								csym.DropObject(osym.References[0], csym.Location, MouseButtons.Right);
						}
						i++;
					}
				}
				#endregion
			}
			ctrler.Show(this.DockPanel);
			ctrler.Save();
		}
		private void doCreateComposite(bool hidden)
		{
			RepositoryService repSvc = (RepositoryService)_wfcontroller.GetService(typeof(RepositoryService));
			if ( repSvc == null )
				throw new NullReferenceException("RepositoryService not available.");

			bool sc;
			bool isNew = false;
			bool isLoadedController = false;
			DesignController ctrler = null;
			if ( _dicNameController.ContainsKey(cComposite) ) {
				ctrler = (DesignController)_dicNameController[cComposite];
				//ctrler.Toolbox.Show();
				//ctrler.Toolbox.Refresh();
				isLoadedController = true;
			} else {
				#region Initialize Composite
				ServiceModule svcmodule = _wfcontroller.Workflow.GetServiceModule();
				BindingListEx<Operation> operations = _wfcontroller.Workflow.GetOperations();
				if ( svcmodule == null || ( operations == null || operations.Count == 0 ) ) {
					//_wfcontroller.Save();
					if ( ( operations == null || operations.Count == 0 ) &&
						 string.IsNullOrEmpty(_wfcontroller.Workflow.StartName) ) {
						if ( _wfcontroller.Workflow.BuildType == WorkflowBuildType.WCF_WindowsForm ) {
							//
							//MessageBox.Show("Please add a Logical Input Event marked as 'Is Start' Event.", "Missing Start Event", MessageBoxButtons.OK, MessageBoxIcon.Warning);
							return;
						} else {
							if ( hidden ) {
								MessageBox.Show(
									"Before the subscriptions can be defined, the capablity that is provided (exposed) by the composite as a whole must now be selected.",
									"Initialization", MessageBoxButtons.OK, MessageBoxIcon.Information);
							} else {
								MessageBox.Show(
									"Before the composite can be defined, the capablity that is provided (exposed) by the composite as a whole must now be selected.",
									"Initialization", MessageBoxButtons.OK, MessageBoxIcon.Information);
							}
							FormSelectRepositoryEx frmSel = new FormSelectRepositoryEx(_wfcontroller);
							frmSel.AllowChangeType = false;
							frmSel.AllowedTypes = new ItemType[] { ItemType.Verb };
							frmSel.DomainID = Global.Status.CurrentDomainId;
							frmSel.RepositoryID = Global.Status.CurrentRepositoryId;
							frmSel.MultiSelect = false;
							if ( frmSel.ShowDialog() != DialogResult.OK ) {
								// cancel
								return;
							}
							Verb v = frmSel.SelectedItem as Verb;
							_wfcontroller.Workflow.BeginEdit();
							_wfcontroller.Workflow.StartName = v.Name;
							_wfcontroller.Workflow.StartDescription = v.Description;
							_wfcontroller.Workflow.InputBusinessObject = v.InputBusinessObject;
							_wfcontroller.Workflow.OutputBusinessObject = v.OutputBusinessObject;
							_wfcontroller.Workflow.ExtendedProperties.WorkflowCapabilityID = v.CapabilityID;
							_wfcontroller.Workflow.ExtendedProperties.WorkflowStartCapabilityMethodID = v.ID;
							#region Add Start Workflow Event
							IRepositoryItem parentItem = null;
							WorkflowEvent we = null;
							if ( _wfcontroller.Workflow.ExtendedProperties.StartEventID > 0 ) {
								we = repSvc.GetItem<WorkflowEvent>(_wfcontroller.Workflow.ExtendedProperties.StartEventID);
								if ( we.WorkflowID < 0 ) {
									we = repSvc.GetNewItem<WorkflowEvent>(false, ref parentItem);
									_wfcontroller.Workflow.ExtendedProperties.StartEventID = we.ID;
								}
							} else {
								we = repSvc.GetNewItem<WorkflowEvent>(false, ref parentItem);
								_wfcontroller.Workflow.ExtendedProperties.StartEventID = we.ID;
							}
							we.BeginEdit();
							we.Name = v.Name;
							we.Description = v.Description;
							we.IsStart = true;
							we.WorkflowID = _wfcontroller.Workflow.ID;
							we.BusinessObjectID = v.InputBusinessObjectID;
							we.EndEdit(true);
							if ( !_wfcontroller.Workflow.Interface.Events.Contains(we) ) {
								_wfcontroller.Workflow.Interface.Events.Add(we);
							}
							#endregion
							#region Add End Workflow Method
							WorkflowMethod wm = null;
							if ( v.OutputBusinessObject != null ) {
								parentItem = null;
								if ( _wfcontroller.Workflow.ExtendedProperties.ReplyMethodID > 0 ) {
									wm = repSvc.GetItem<WorkflowMethod>(_wfcontroller.Workflow.ExtendedProperties.ReplyMethodID);
									if ( wm.WorkflowID < 0 ) {
										wm = repSvc.GetNewItem<WorkflowMethod>(false, ref parentItem);
										_wfcontroller.Workflow.ExtendedProperties.ReplyMethodID = wm.ID;
									}
								} else {
									wm = repSvc.GetNewItem<WorkflowMethod>(false, ref parentItem);
									_wfcontroller.Workflow.ExtendedProperties.ReplyMethodID = wm.ID;
								}
								wm.BeginEdit();
								wm.Name = v.Name + Deployment.c_Reply;
								wm.Description = "This returns the output of this process to the process starter" +
									Environment.NewLine + v.Description;
								wm.WorkflowID = _wfcontroller.Workflow.ID;
								wm.InputBusinessObjectID = v.OutputBusinessObjectID;
								wm.EndEdit(true);
								if ( !_wfcontroller.Workflow.Interface.Methods.Contains(wm) ) {
									_wfcontroller.Workflow.Interface.Methods.Add(wm);
								}
							}
							#endregion
							_wfcontroller.Workflow.EndEdit(true);
							_wfcontroller.Save();
							_wfcontroller.WorkflowLoader.AddStartEndActivities(we, wm);
							_wfcontroller.WorkflowLoader.RefreshAllCode();
							#region old code
							//// config start operation
							//FormCreateProcess frm = new FormCreateProcess(_wfcontroller);
							//frm.Text = "Define Start Capability";
							//frm.ProcessName = "Start";
							//frm.ProcessDescription = "This is the start capability of the business process.";
							//if ( frm.ShowDialog() != DialogResult.OK ) {
							//    // cancel
							//    return;
							//}
							//_wfcontroller.Workflow.StartName = frm.ProcessName;
							//_wfcontroller.Workflow.StartDescription = frm.ProcessDescription;
							//_wfcontroller.Workflow.InputBusinessObject = frm.InputBusinessObject;
							//_wfcontroller.Workflow.OutputBusinessObject = frm.OutputBusinessObject;
							#endregion
						}
					}
					if ( svcmodule == null ) {
						IRepositoryItem parentItem = null;
						svcmodule = repSvc.GetNewItem<ServiceModule>(false, ref parentItem);
						if ( svcmodule == null ) {
							MessageBox.Show("Failed to create Composite.");
							return;
						}
						svcmodule.WorkflowID = _wfcontroller.Workflow.ID;
						svcmodule.Name = _wfcontroller.ClassName;
						svcmodule.Type = ServiceModuleType.Composite;
						svcmodule.CreatedType = CreatedTypeFlags.RecursiveDeleteAllowed;
						svcmodule.Save();
						//Global.Data.AddRepositoryItemToDomainFolder(Global.Status.CurrentDomainId, svcmodule);
						isNew = true;
					}
				}
				#endregion

				ctrler = repSvc.CreateDesignController(this.DockPanel, svcmodule, Global.Status.CurrentRepositoryId) as DesignController;
				if ( ctrler == null ) {
					MessageBox.Show("RepositoryFactory.CreateDesignController failed.");
					return;
				}
				ctrler.ToolboxCategory = "Service";
				if ( !hidden ) {
					IMainController mainCtrler = _wfcontroller.GetService(typeof(IMainController)) as IMainController;
					if ( mainCtrler != null ) {
						mainCtrler.RegisterControllerEvents(ctrler);
					}
					_dicNameController.Add(cComposite, ctrler);
					//ctrler.Toolbox.Show(_wfcontroller.ToolboxForm.Pane, _wfcontroller.ToolboxForm);
					//ctrler.Toolbox.Refresh();
				}
			}
			if ( ctrler == null ) {
				MessageBox.Show("DesignController Initialization failed.");
				return;
			}
			List<OpenComposite.Workflow.LogicalCapabilityActivity> lstLogActs = getLogicalCapabilityActivities();
			if ( isNew ) {
				#region Create New Composite
				ServiceModuleSymbol ctrlMain = ctrler.DesignerView.MainControl as ServiceModuleSymbol;
				if ( ctrlMain == null ) {
					MessageBox.Show("MainControl is not a ServiceModuleSymbol.");
					return;
				}
				// add orchestration component
				Service svcOrch = repSvc.GetItem(ItemType.OrchestrationComponent, true, Global.Status.CurrentRepositoryId, false, false, out sc) as Service;
				OrchestrationComponentSymbol osym = null;
				if ( svcOrch != null ) {
					svcOrch.Name = _wfcontroller.ClassName;
					svcOrch.CreatedType = CreatedTypeFlags.RecursiveDeleteAllowed;
					osym = repSvc.CreateDesignerControl(svcOrch) as OrchestrationComponentSymbol;
					if ( osym != null ) {
						osym.Location = new Point(100, 50);
						osym.ProcessOperation = repSvc.GetItem(ItemType.Operation, true, Global.Status.CurrentRepositoryId, false, false, out sc) as Operation;
						if ( osym.Interfaces.Count > 0 )
							osym.Interfaces[0].Operations.Add(osym.ProcessOperation);
						if ( osym.ProcessOperation != null ) {
							osym.ProcessOperation.Name = _wfcontroller.Workflow.StartName;
							osym.ProcessOperation.Description = _wfcontroller.Workflow.StartDescription;
							osym.ProcessOperation.SetInputBusinessObject(_wfcontroller.Workflow.InputBusinessObject);
							osym.ProcessOperation.SetOutputBusinessObject(_wfcontroller.Workflow.OutputBusinessObject);
							osym.ProcessOperation.WorkflowId = _wfcontroller.Workflow.ID;
						}
						ctrlMain.IsCollapsed = false;
						ctrlMain.Controls.Add(osym);
						if ( ctrlMain.Interfaces.Count > 0 && osym.Interfaces.Count > 0 )
							ctrlMain.Interfaces[0].DropObject(osym.Interfaces[0], ctrlMain.Interfaces[0].Location, MouseButtons.Right);
					}
				}
				// add capability symbols
				for ( int i = 0; i < lstLogActs.Count; i++ ) {
					LogicalActivity lact = repSvc.GetItem<LogicalActivity>(lstLogActs[i].LogicalActivityId);
					if ( lact == null ) continue;
					CapabilitySymbol csym = repSvc.CreateDesignerControl(lact) as CapabilitySymbol;
					if ( csym != null ) {
						csym.Location = new Point(300, 20 + ( i * 60 ));
						ctrlMain.Controls.Add(csym);
						if ( osym != null ) {
							if ( osym.References.Count == 0 )
								csym.DropObject(osym, csym.Location, MouseButtons.Right);
							else
								csym.DropObject(osym.References[0], csym.Location, MouseButtons.Right);
						}
					}
				}
				//_wfcontroller.LoadWorkflow(_wfcontroller.Workflow);
				_wfcontroller.Save();
				_wfcontroller.IsChanged = true;
				#endregion
			} else {
				#region Check Existing Composite
				ServiceModuleSymbol ctrlMain = ctrler.DesignerView.MainControl as ServiceModuleSymbol;
				if ( ctrlMain == null &&
					 ctrler.DesignerView.DesignerControls.ControlsWithoutRoutes.Count == 1 ) {
					ctrlMain = ctrler.DesignerView.DesignerControls.ControlsWithoutRoutes[0] as ServiceModuleSymbol;
				}
				if ( ctrlMain == null ) {
					ctrler.RepositoryItem.DeleteInternal();
					doCreateComposite(hidden);
					//MessageBox.Show("MainControl is not a ServiceModuleSymbol.");
					return;
				}
				int i = 0;
				OrchestrationComponentSymbol osym = null;
				List<CapabilitySymbol> lstDeletedCaps = new List<CapabilitySymbol>();
				List<OpenComposite.Workflow.LogicalCapabilityActivity> lstNewLogCaps =
					new List<OpenComposite.Workflow.LogicalCapabilityActivity>(lstLogActs);
				SortedList<int, WorkflowReferenceSymbol> existingWorkflowSymbols = new SortedList<int, WorkflowReferenceSymbol>();
				//int ypos = 0;
				foreach ( DesignerControl ctrl in ctrlMain.Controls ) {
					WorkflowReferenceSymbol workflowRef = ctrl as WorkflowReferenceSymbol;
					if ( workflowRef != null ) {
						if ( !existingWorkflowSymbols.ContainsKey(workflowRef.RepositoryItem.ID) ) {
							existingWorkflowSymbols.Add(workflowRef.RepositoryItem.ID, workflowRef);
						}
					}
				}
				foreach ( DesignerControl ctrl in ctrlMain.Controls.ToArray() ) {
					if ( ctrl is OrchestrationComponentSymbol && osym == null ) {
						osym = (OrchestrationComponentSymbol)ctrl;
						continue;
					}
					CapabilitySymbol csym = ctrl as CapabilitySymbol;
					if ( csym != null ) {
						bool exists = false;
						if ( csym.RepositoryItem != null ) {
							i++;
							foreach ( OpenComposite.Workflow.LogicalCapabilityActivity lgcap in lstLogActs ) {
								if ( lgcap.LogicalActivityId > 0 ) {
									LogicalActivity lact = repSvc.GetItem<LogicalActivity>(lgcap.LogicalActivityId);
									if ( lact != null && lact.ID == csym.RepositoryItem.ID ) {
										exists = true;
										lstNewLogCaps.Remove(lgcap);
										break;
									}
								}
							}
						}
						if ( !exists ) {
							lstDeletedCaps.Add(csym);
						} else {
							if ( csym.Operation != null ) {
								bool isConnected = false;
								foreach ( Route route in ctrlMain.DesignerViewControl.DesignerControls.Routes ) {
									if ( route.StartControl == csym && route.EndControl is ExposedCapabilitySymbol ) {
										isConnected = true;
										break;
									}
								}
								if ( isConnected ) continue;
								if ( existingWorkflowSymbols.ContainsKey(csym.Operation.ExposedWorkflowId) ) {
									ctrlMain.DesignerViewControl.AddRoute(csym, existingWorkflowSymbols[csym.Operation.ExposedWorkflowId]);
								} else {
									Repository.Workflow wf = repSvc.GetItem<Repository.Workflow>(csym.Operation.ExposedWorkflowId);
									if ( wf != null ) {
										WorkflowReferenceSymbol wrs = repSvc.CreateDesignerControl(wf) as WorkflowReferenceSymbol;
										if ( wrs != null ) {
											wrs.Location = csym.Location + new Size(100, -( ( wrs.Height / 2 ) - ( csym.Height / 2 ) ));
											wrs.IsReference = true;
											ctrlMain.Controls.Add(wrs);
											existingWorkflowSymbols.Add(wf.ID, wrs);
											if ( wrs.ExposedCapabilitySymbol != null ) {
												Route route = ctrlMain.DesignerViewControl.AddRoute(wrs.ExposedCapabilitySymbol, csym);
												route.StartDockDirection = RouteDockDirection.Left;
											}
										}
									}
								}
							}
						}
					}
				}
				if ( lstDeletedCaps.Count > 0 ) _wfcontroller.IsChanged = true;
				foreach ( CapabilitySymbol csym in lstDeletedCaps ) {
					csym.Remove();
				}
				if ( osym == null ) {
					// add orchestration component
					Service svcOrch = repSvc.GetItem(ItemType.OrchestrationComponent, true, Global.Status.CurrentRepositoryId, false, false, out sc) as Service;
					if ( svcOrch != null ) {
						svcOrch.Name = _wfcontroller.ClassName;
						svcOrch.CreatedType = CreatedTypeFlags.RecursiveDeleteAllowed;
						osym = repSvc.CreateDesignerControl(svcOrch) as OrchestrationComponentSymbol;
						if ( osym != null ) {
							osym.Location = new Point(100, 50);
							osym.ProcessOperation = repSvc.GetItem(ItemType.Operation, true, Global.Status.CurrentRepositoryId, false, false, out sc) as Operation;
							if ( osym.Interfaces.Count > 0 )
								osym.Interfaces[0].Operations.Add(osym.ProcessOperation);
							if ( osym.ProcessOperation != null ) {
								osym.ProcessOperation.Name = _wfcontroller.Workflow.StartName;
								osym.ProcessOperation.Description = _wfcontroller.Workflow.StartDescription;
								osym.ProcessOperation.SetInputBusinessObject(_wfcontroller.Workflow.InputBusinessObject);
								osym.ProcessOperation.SetOutputBusinessObject(_wfcontroller.Workflow.OutputBusinessObject);
								osym.ProcessOperation.WorkflowId = _wfcontroller.Workflow.ID;
							}
							ctrlMain.Controls.Add(osym);
							if ( ctrlMain.Interfaces.Count > 0 && osym.Interfaces.Count > 0 )
								ctrlMain.Interfaces[0].DropObject(osym.Interfaces[0], ctrlMain.Interfaces[0].Location, MouseButtons.Right);
							_wfcontroller.IsChanged = true;
						}
					}
				}

				if ( lstNewLogCaps.Count > 0 ) _wfcontroller.IsChanged = true;
				foreach ( OpenComposite.Workflow.LogicalCapabilityActivity logcap in lstNewLogCaps ) {
					LogicalActivity lact = repSvc.GetItem<LogicalActivity>(logcap.LogicalActivityId);
					if ( lact == null ) continue;
					CapabilitySymbol csym = repSvc.CreateDesignerControl(lact) as CapabilitySymbol;
					if ( csym != null ) {
						csym.Location = new Point(300, 20 + ( i * 60 ));
						ctrlMain.Controls.Add(csym);
						if ( osym != null ) {
							if ( osym.References.Count == 0 )
								csym.DropObject(osym, csym.Location, MouseButtons.Right);
							else
								csym.DropObject(osym.References[0], csym.Location, MouseButtons.Right);
						}
						i++;
					}
				}
				#endregion
			}
			if ( hidden ) {
				ctrler.Save();
				if ( !isLoadedController ) {
					//ctrler.Close();
					if ( _dicNameController.ContainsKey(cComposite) ) {
						_dicNameController.Remove(cComposite);
					}
				}
			} else {
				//ctrler.Show(this.DockPanel);
				Control c = ctrler.GetView(ViewTechnology.Default) as Control;
				Debug.Assert(c != null);
				if ( !tabComposite.Contains(c) ) {
					c.Dock = DockStyle.Fill;
					tabComposite.Controls.Add(c);
				}
				ctrler.Save();
			}
		}
		private void displayDeploy()
		{
			if ( _wfcontroller.Workflow != null ) {
				if ( !string.IsNullOrEmpty(_wfcontroller.Workflow.Path) &&
				 Directory.Exists(_wfcontroller.Workflow.Path) ) {
					txtTargetFolder.Text = _wfcontroller.Workflow.Path;
				} else {
					txtTargetFolder.Text = "";
				}
				//if ( _wfcontroller.Workflow.ExtendedProperties.ConfigurationLevel == ConfigurationLevel.CompleteCodeGeneration ) {
				//    rbGenTypeCode.Checked = true;
				//} else {
				//    rbGenTypeConfig.Checked = true;
				//}
			}
			UCTaskErrorListService c = null;
			if ( _wfcontroller != null && groupTasksErrors.Controls.Count == 0 ) {
				ITaskListService tls = _wfcontroller.GetService(typeof(ITaskListService)) as ITaskListService;
				if ( tls != null ) {
					c = tls.GetView(_wfcontroller.Workflow) as UCTaskErrorListService;
					if ( c != null && !groupTasksErrors.Contains(c) ) {
						c.Dock = DockStyle.Fill;
						c.RefreshTaskList += new EventHandler(TaskListService_RefreshTaskList);
						c.RefreshButtonVisible = true;
						groupTasksErrors.Controls.Add(c);
						groupTasksErrors.Refresh();
					}
				}
			}
			doValidation();
			displayConfigurableElements();
			if ( c != null ) c.RefreshTasks();
		}

		private void doValidation()
		{
			IWorkflowValidator wv = _wfcontroller.GetService(typeof(IWorkflowValidator)) as IWorkflowValidator;
			if ( wv != null ) {
				if ( !_isWValidatorInitialized ) {
					wv.ValidationCompleted += new EventHandler(wv_ValidationCompleted);
					_isWValidatorInitialized = true;
				}
				wv.DoValidation();
			}
		}

		private void saveTab(TabPage tabToSave)
		{
			using ( new WaitMouse() ) {
				// save the selected tab item
				if ( tabToSave == tabWorkflow ) {
					// save workflow
					_wfcontroller.Save();
				} else if ( tabToSave == tabProcFlowPolicy ) {
					// save Process Flow Policy
					_dicNameController[cFlowPolicy].Save();
				} else if ( tabToSave == tabParticipantPolicy ) {
					// save Participant Policy
					_dicNameController[cParticipantPolicy].Save();
				} else if ( tabToSave == tabSubscriptions ) {
					// save Subscriptions
					_dicNameController[cSubscriptions].Save();
				} else if ( tabToSave == tabBinding ) {
					// save workflow
					_wfcontroller.Save();
				} else if ( tabToSave == tabComposite ) {
					// save Composite
					if ( _dicNameController.ContainsKey(cComposite) ) {
						_dicNameController[cComposite].Save();
					}
				} else if ( tabToSave == tabDeploy ) {
					// save workflow
					_wfcontroller.Save();
				}
			}
		}
		private void showTab(TabPage tabToShow)
		{
			this.SuspendLayout();
			try {
				RepositorySurfaceManager rsm = _wfcontroller.GetService(typeof(RepositorySurfaceManager)) as RepositorySurfaceManager;
				using ( new WaitMouse() ) {
					if ( _toolBoxService == null ) {
						_toolBoxService = _wfcontroller.GetService(typeof(IToolboxService)) as MainToolboxService;
					}
					if ( _toolBoxService != null ) {
						if ( tabToShow == tabWorkflow ) {
							_toolBoxService.Show();
						} else {
							_toolBoxService.Hide();
						}
					}
					if ( _wfcontroller.PropertiesForm != null ) {
						if ( tabToShow == tabWorkflow ) {
							_wfcontroller.PropertiesForm.Show();
						} else {
							_wfcontroller.PropertiesForm.Hide();
						}
					}
					if ( tabToShow == tabWorkflow ) {
						if ( rsm != null ) {
							_wfcontroller.ToolboxCategory = _wfToolboxCategory;
							rsm.ActiveDesignSurface = _wfcontroller.Surface;
							this.ActiveSurface = _wfcontroller.Surface;
						}
						//_wfcontroller.ToolboxForm.Show();
					} else if ( tabToShow == tabProcFlowPolicy ) {
						showProcessPolicy();
						setActiveSurface(rsm, cFlowPolicy);
					} else if ( tabToShow == tabParticipantPolicy ) {
						showParticipantPolicy();
						setActiveSurface(rsm, cParticipantPolicy);
					} else if ( tabToShow == tabSubscriptions ) {
						showBUSView();
						setActiveSurface(rsm, cSubscriptions);
					} else if ( tabToShow == tabBinding ) {
						showBinding();
					} else if ( tabToShow == tabComposite ) {
						doCreateComposite(false);
						setActiveSurface(rsm, cComposite);
					} else if ( tabToShow == tabDeploy ) {
						displayDeploy();
					}
				}
			} finally {
				this.ResumeLayout(true);
				this.DockPanel.Refresh();
				this.Refresh();
			}
		}

		private void setActiveSurface(RepositorySurfaceManager rsm, string controllerName)
		{
			IController c = _dicNameController[controllerName];
			if ( rsm != null && c != null ) {
				_wfcontroller.ToolboxCategory = c.ToolboxCategory;
				rsm.ActiveDesignSurface = c.Surface;
				this.ActiveSurface = c.Surface;
				if ( _toolBoxService == null ) {
					_toolBoxService = _wfcontroller.GetService(typeof(IToolboxService)) as MainToolboxService;
				}
				if ( _toolBoxService != null ) {
					if ( string.IsNullOrEmpty(c.ToolboxCategory) ) {
						_toolBoxService.Hide();
					} else {
						_toolBoxService.Show();
					}
				}
			}
		}

		private BUSActivitySymbol addBUSActivity(LogicalActivity logact, DesignerViewControl view, BUSSymbol bus,
									ref int iTopMaxX, ref int iBottomMaxX)
		{
			if ( logact == null ) return null;
			bool exists = false;
			BUSActivitySymbol busact = null;
			RepositoryService repSvc = this.Repository;
			foreach ( DesignerControl dc in view.DesignerControls ) {
				busact = dc as BUSActivitySymbol;
				if ( busact != null && busact.LogicalActivity != null &&
					 busact.LogicalActivity.ID == logact.ID ) {
					exists = true;
					if ( busact.Right > view.MainPanel.Width / view.ZoomFactor ) {
						busact.Left = (int)( view.MainPanel.Width / view.ZoomFactor - busact.Width );
					}
					break;
				}
			}
			if ( exists ) {
				return busact;
			}
			const int padx = 50;
			busact = repSvc.CreateDesignerControl(ItemType.BUSActivity, false) as BUSActivitySymbol;
			if ( busact != null ) {
				Verb v = logact.Verb;
				Operation o = logact.GetAssignedOperation();
				WorkflowMethod wm = logact.GetWorkflowMethod();
				WorkflowEvent we = logact.GetWorkflowEvent();
				if ( ( v != null && v.OutputBusinessObjectID > 0 ) ||
					 ( o != null && o.OutputBusinessObjectId > 0 ) ||
					 ( wm != null && wm.InputBusinessObjectID > 0 ) ||
					 ( we != null && we.BusinessObjectID > 0 ) ||
					logact.OutputBusinessObjectID > 0 ) {
					busact.Location = new Point(iTopMaxX + padx,
											   bus.Top - 100 - busact.Height);
					iTopMaxX += ( padx + busact.Width );
				} else {
					busact.Location = new Point(iBottomMaxX + padx,
											   bus.Bottom + 100);
					iBottomMaxX += ( padx + busact.Width );
				}
				view.AddDesignerControl(busact);

				busact.BUS = bus;
				busact.LogicalActivity = logact;
				busact.Load(Global.Status.CurrentRepositoryId, Global.Status.CurrentDomainId);
			}
			return busact;
		}

		private List<OpenComposite.Workflow.LogicalCapabilityActivity> getLogicalCapabilityActivities()
		{
			List<OpenComposite.Workflow.LogicalCapabilityActivity> lstLogActs = new List<OpenComposite.Workflow.LogicalCapabilityActivity>();
			System.Workflow.ComponentModel.CompositeActivity composite = _wfcontroller.WorkflowView.RootDesigner.Activity as System.Workflow.ComponentModel.CompositeActivity;
			if ( composite != null ) {
				foreach ( System.Workflow.ComponentModel.Activity act in Helpers.GetNestedActivities(composite) ) {
					if ( act is OpenComposite.Workflow.LogicalCapabilityActivity )
						lstLogActs.Add((OpenComposite.Workflow.LogicalCapabilityActivity)act);
				}
			}
			return lstLogActs;
		}
		private List<T> getLogicalActivities<T>() where T : System.Workflow.ComponentModel.Activity
		{
			List<T> lstLogActs = new List<T>();
			System.Workflow.ComponentModel.CompositeActivity composite =
				_wfcontroller.WorkflowView.RootDesigner.Activity as System.Workflow.ComponentModel.CompositeActivity;
			if ( composite != null ) {
				foreach ( System.Workflow.ComponentModel.Activity act in
							Helpers.GetNestedActivities(composite) ) {
					if ( act is T )
						lstLogActs.Add((T)act);
				}
			}
			return lstLogActs;
		}
		private List<OpenComposite.Workflow.LogicalEPActivity> getLogicalEPActivities()
		{
			List<OpenComposite.Workflow.LogicalEPActivity> lstLogActs = new List<OpenComposite.Workflow.LogicalEPActivity>();
			System.Workflow.ComponentModel.CompositeActivity composite = _wfcontroller.WorkflowView.RootDesigner.Activity as System.Workflow.ComponentModel.CompositeActivity;
			if ( composite != null ) {
				foreach ( System.Workflow.ComponentModel.Activity act in Helpers.GetNestedActivities(composite) ) {
					if ( act is OpenComposite.Workflow.LogicalEPActivity )
						lstLogActs.Add((OpenComposite.Workflow.LogicalEPActivity)act);
				}
			}
			return lstLogActs;
		}
		private List<OpenComposite.Workflow.DataAggregatorActivity> getDataAggregatorActivities()
		{
			List<OpenComposite.Workflow.DataAggregatorActivity> lstLogActs = new List<OpenComposite.Workflow.DataAggregatorActivity>();
			System.Workflow.ComponentModel.CompositeActivity composite = _wfcontroller.WorkflowView.RootDesigner.Activity as System.Workflow.ComponentModel.CompositeActivity;
			if ( composite != null ) {
				foreach ( System.Workflow.ComponentModel.Activity act in Helpers.GetNestedActivities(composite) ) {
					if ( act is OpenComposite.Workflow.DataAggregatorActivity )
						lstLogActs.Add((OpenComposite.Workflow.DataAggregatorActivity)act);
				}
			}
			return lstLogActs;
		}
		private List<OpenComposite.Workflow.RuleEvaluatorActivity> getRuleEvaluatorActivities()
		{
			List<OpenComposite.Workflow.RuleEvaluatorActivity> lstLogActs = new List<OpenComposite.Workflow.RuleEvaluatorActivity>();
			System.Workflow.ComponentModel.CompositeActivity composite = _wfcontroller.WorkflowView.RootDesigner.Activity as System.Workflow.ComponentModel.CompositeActivity;
			if ( composite != null ) {
				foreach ( System.Workflow.ComponentModel.Activity act in Helpers.GetNestedActivities(composite) ) {
					if ( act is OpenComposite.Workflow.RuleEvaluatorActivity )
						lstLogActs.Add((OpenComposite.Workflow.RuleEvaluatorActivity)act);
				}
			}
			return lstLogActs;
		}

		private void getLogicalActivities(
			out List<LogicalCapabilityActivity> listLogCaps,
			out List<LogicalInputActivity> listLogInActs,
			out List<LogicalMethodCallActivity> listLogMeths,
			out List<DataAggregatorActivity> listDataAggrs,
			out List<RuleEvaluatorActivity> listReas,
			out List<NotificationActivity> listNotiActs)
		{
			listLogCaps = new List<LogicalCapabilityActivity>();
			listLogInActs = new List<LogicalInputActivity>();
			listLogMeths = new List<LogicalMethodCallActivity>();
			listDataAggrs = new List<DataAggregatorActivity>();
			listReas = new List<RuleEvaluatorActivity>();
			listNotiActs = new List<NotificationActivity>();

			System.Workflow.ComponentModel.CompositeActivity composite = _wfcontroller.WorkflowView.RootDesigner.Activity as System.Workflow.ComponentModel.CompositeActivity;
			if ( composite != null ) {
				foreach ( System.Workflow.ComponentModel.Activity act in Helpers.GetNestedActivities(composite) ) {
					if ( act is LogicalCapabilityActivity ) {
						listLogCaps.Add((LogicalCapabilityActivity)act);
					} else if ( act is LogicalInputActivity ) {
						listLogInActs.Add((LogicalInputActivity)act);
					} else if ( act is LogicalMethodCallActivity ) {
						listLogMeths.Add((LogicalMethodCallActivity)act);
					} else if ( act is DataAggregatorActivity ) {
						listDataAggrs.Add((DataAggregatorActivity)act);
					} else if ( act is RuleEvaluatorActivity ) {
						listReas.Add((RuleEvaluatorActivity)act);
					} else if ( act is NotificationActivity ) {
						listNotiActs.Add((NotificationActivity)act);
					}
				}
			}
		}

		private string getDefaultWorkflow(string name)
		{
			name = RepositoryService.GetIdentifier(name);
			string xml = null;
			Activity workflow;
			if ( _wfcontroller.Workflow.Type == WorkflowType.Business_Process ||
				 _wfcontroller.Workflow.Type == WorkflowType.Mashup_Horizontal ) {
				workflow = new HorizontalWorkflowActivity();
			} else {
				workflow = new SequentialWorkflowActivity();
			}
			//StateMachineWorkflowActivity workflow = new StateMachineWorkflowActivity();
			workflow.Name = name;
			workflow.SetValue(WorkflowMarkupSerializer.XClassProperty,
				string.Format("{0}.{1}", "OpenComposite.Orchestration", name));
			XmlWriterSettings xws = new XmlWriterSettings();
			xws.ConformanceLevel = ConformanceLevel.Fragment;
			using ( StringWriter sw = new StringWriter() )
			using ( XmlWriter xmlWriter = XmlTextWriter.Create(sw, xws) ) {
				WorkflowMarkupSerializer serializer = new WorkflowMarkupSerializer();
				serializer.Serialize(xmlWriter, workflow);
				xmlWriter.Flush();
				xml = sw.ToString();
			}
			return xml;
		}

		private void displayConfigurableElements()
		{
			//txtElements.SuspendLayout();
			//if ( _wfcontroller.Workflow.ExtendedProperties != null && _wfcontroller.Workflow.ExtendedProperties.ConfigurableElements != null &&
			//     _wfcontroller.Workflow.ExtendedProperties.ConfigurableElements.Count > 0 ) {
			//    txtElements.Text = _wfcontroller.Workflow.ExtendedProperties.GetConfigurableElementsString();
			//    txtElements.TextAlign = HorizontalAlignment.Left;
			//} else {
			//    txtElements.Text = string.Format(
			//        "Please select the elements for the {0} configuration.",
			//        _wfcontroller.Workflow.TypeString.ToLower());
			//    txtElements.TextAlign = HorizontalAlignment.Center;
			//}
			//txtElements.ResumeLayout(true);
		}

		#endregion

		#region Event Handlers

		#region Form
		private void FormWorkflowDesigner_FormClosing(object sender, FormClosingEventArgs e)
		{

		}
		#endregion

		#region Workflow Controller
		private void _wfcontroller_Loaded(object sender, EventArgs e)
		{
			if ( _wfcontroller.Workflow == null )
				return;

			_isLoading = true;

			try {
				bool isBProc = ( _wfcontroller.Workflow.Type == WorkflowType.Business_Process );
				bool isMashup = ( _wfcontroller.Workflow.Type == WorkflowType.Mashup );
				bool isComposite = ( _wfcontroller.Workflow.Type == WorkflowType.Orchestration );
				bool isMashupBP = ( _wfcontroller.Workflow.Type == WorkflowType.Mashup_Horizontal );
				//tssepGenerateSOBA.Visible = isBProc;
				//tsbtnGenerateSOBA.Visible = isBProc;
				//tssepSOBA.Visible = isBProc || isComposite;
				//tsmiSOBAView.Visible = isBProc;
				//tsmiCompositeView.Visible = isComposite;

				// change ui for workflow type
				if ( isBProc ) {
					// soba workflow (business process)
					//tsmiDeploy.Text = "Deploy / Update SOBA";
					//tsmiRedeploy.Text = "Redeploy SOBA";
					tabWorkflow.Text = "Business Process";
					tabWorkflow.ImageKey = "horizontalprocess";
					tsmiSimulation.Visible = true;
					tsmiShowInterface.Text = "Show Interface";
				} else if ( isMashup || isMashupBP ) {
					// mashup workflow
					//tsmiDeploy.Text = "Deploy / Update Mashup";
					//tsmiRedeploy.Text = "Redeploy Mashup";
					tsmiShowInterface.Text = "Show Interface";
					tabCtrlWorkflow.TabPages.Remove(tabComposite);
				} else {
					// composite workflow (orchestration)
					//tsmiDeploy.Text = "Deploy / Update Composite";
					//tsmiRedeploy.Text = "Redeploy Composite";
					tsmiSimulation.Visible = true;
					tsmiShowInterface.Text = "Show Interface";
				}

				tsmiViewVertical.Visible = isMashupBP;
				tsmiViewHorizontal.Visible = isMashup;

				// fill BuildType Combo
				tscmbBuildType.BeginUpdate();
				tscmbBuildType.Items.Clear();
				WFBuildTypeItem selected = null;
				foreach ( WorkflowBuildType type in _wfcontroller.Workflow.AllowedBuildTypes ) {
					WFBuildTypeItem item = new WFBuildTypeItem(type);
					if ( type == _wfcontroller.Workflow.BuildType )
						selected = item;
					tscmbBuildType.Items.Add(item);
				}
				if ( selected == null )
					tscmbBuildType.SelectedIndex = 0;
				else
					tscmbBuildType.SelectedItem = selected;
				tscmbBuildType.EndUpdate();
				//if ( isComposite ) {
				//    doCreateComposite(true);
				//}
				ITaskListService tls = _wfcontroller.GetService(typeof(ITaskListService)) as ITaskListService;
				if ( tls != null ) {
					tls.TaskItemAction += new ITaskItemEventHandler(tls_TaskItemAction);
				}
			} finally {
				_isLoading = false;
			}
		}

		private void _wfcontroller_Closing(object sender, CancelEventArgs e)
		{
			foreach ( IController ctrler in _dicNameController.Values ) {
				if ( ctrler != _wfcontroller ) {
					ctrler.Save();
					ctrler.Close();
				}
			}
			ITaskListService tls = _wfcontroller.GetService(typeof(ITaskListService)) as ITaskListService;
			if ( tls != null ) {
				UCTaskErrorListService c = tls.GetView(_wfcontroller.Workflow) as UCTaskErrorListService;
				if ( c != null ) c.RefreshTaskList -= new EventHandler(TaskListService_RefreshTaskList);
				tls.TaskItemAction -= new ITaskItemEventHandler(tls_TaskItemAction);
			}
		}

		#endregion

		#region ToolStrip
		private void tsbtnSave_Click(object sender, EventArgs e)
		{
			saveTab(tabCtrlWorkflow.SelectedTab);
		}

		private void tscmbBuildType_SelectedIndexChanged(object sender, EventArgs e)
		{
			WFBuildTypeItem item = tscmbBuildType.SelectedItem as WFBuildTypeItem;
			if ( item != null ) {
				_wfcontroller.Workflow.BuildType = item.BuildType;
				tscmbBuildType.ToolTipText = item.ToString();
				if ( !_isLoading )
					_wfcontroller.Save();
			}
		}

		private void tsbtnCompile_Click(object sender, EventArgs e)
		{
			if ( Form.ModifierKeys != Keys.Shift ) {
				tabCtrlWorkflow.SelectedTab = tabDeploy;
			}
			tabDeploy.Refresh();
			this.Refresh();
			_wfcontroller.CompileWorkflow();
		}
		private void tsbtnDeploy_Click(object sender, EventArgs e)
		{
			doDeploy(true);
		}
		private void tsmiRedeploy_Click(object sender, EventArgs e)
		{
			DialogResult result =
				MessageBox.Show("All external changes will be deleted." + Environment.NewLine + Environment.NewLine +
								"Do you want to coninue?", tsmiRedeploy.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
			if ( result == DialogResult.Yes ) {
				doDeploy(false);
			}
		}

		private void tsbtnSimulation_Click(object sender, EventArgs e)
		{
			doSimulation();
		}
		private void tsbtnBUSView_Click(object sender, EventArgs e)
		{
			showBUSView();
		}

		private void tsmiProcessPolicy_Click(object sender, EventArgs e)
		{
			showProcessPolicy();
		}
		private void tsmiParticipantPolicy_Click(object sender, EventArgs e)
		{
			showParticipantPolicy();
		}
		private void tsmiBindingMapping_Click(object sender, EventArgs e)
		{
			showBinding();
		}
		private void tsbtnGenerateSOBA_Click(object sender, EventArgs e)
		{
			doCreateSOBA();
		}
		private void tsmiCompositeView_Click(object sender, EventArgs e)
		{
			doCreateComposite(false);
		}

		private void tsmiShowToolbox_Click(object sender, EventArgs e)
		{
			MainToolboxService mts = _wfcontroller.GetService(typeof(IToolboxService)) as MainToolboxService;
			if ( mts != null ) mts.Show();
		}
		private void tsmiShowProperties_Click(object sender, EventArgs e)
		{
			_wfcontroller.PropertiesForm.Show(this.DockPanel);
		}
		private void tsmiShowInterface_Click(object sender, EventArgs e)
		{
			_wfcontroller.InterfaceForm.Show(this.DockPanel);
			_wfcontroller.HideInterfaceForm = false;
		}

		private void tsmiVerticalView_Click(object sender, EventArgs e)
		{
			DialogResult res = MessageBox.Show("This action will delete all activities in your process. Continue?",
				"Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk);
			if ( res == DialogResult.Yes ) {
				_wfcontroller.Workflow.Type = WorkflowType.Mashup;
				MainToolboxService mbs = _wfcontroller.GetService(typeof(IToolboxService)) as MainToolboxService;
				mbs.SelectedCategory = "Workflow";
				_wfcontroller.Workflow.XOML = getDefaultWorkflow(_wfcontroller.Workflow.Name);
				_wfcontroller.Workflow.Save();
				_wfcontroller.LoadWorkflow(_wfcontroller.Workflow);
				_wfcontroller.Show(_wfcontroller.DockPanel);
				_wfcontroller.Workflow.BuildType = WorkflowBuildType.WCF_WindowsForm;

				tsmiViewHorizontal.Visible = true;
				tsmiViewVertical.Visible = false;
			}

		}
		private void tsmiHorizontalView_Click(object sender, EventArgs e)
		{
			DialogResult res = MessageBox.Show("This action will delete all activities in your process. Continue?",
				"Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk);
			if ( res == DialogResult.Yes ) {
				_wfcontroller.Workflow.Type = WorkflowType.Mashup_Horizontal;
				MainToolboxService mbs = _wfcontroller.GetService(typeof(IToolboxService)) as MainToolboxService;
				mbs.SelectedCategory = "Business Process";
				_wfcontroller.Workflow.XOML = getDefaultWorkflow(_wfcontroller.Workflow.Name);
				_wfcontroller.Workflow.Save();
				_wfcontroller.LoadWorkflow(_wfcontroller.Workflow);
				_wfcontroller.Show(_wfcontroller.DockPanel);
				_wfcontroller.Workflow.BuildType = WorkflowBuildType.WCF_WindowsForm;

				tsmiViewHorizontal.Visible = false;
				tsmiViewVertical.Visible = true;
			}
		}

		private void tsmiCreateCompositeApp_Click(object sender, EventArgs e)
		{
			doCreateComposite(false);
		}

		private void tsmiCreateComposite_Click(object sender, EventArgs e)
		{
			doCreateComposite(false);
		}

		private void tsbtnPageSetup_Click(object sender, EventArgs e)
		{
			System.Workflow.ComponentModel.Design.WorkflowPageSetupDialog dlg =
				new System.Workflow.ComponentModel.Design.WorkflowPageSetupDialog(_wfcontroller.WorkflowView as IServiceProvider);
			// HACK: enable visual style backcolor
			TabControl tabC = dlg.Controls[1] as TabControl;
			if ( tabC != null ) {
				foreach ( TabPage page in tabC.TabPages ) {
					page.UseVisualStyleBackColor = true;
				}
			}
			if ( dlg.ShowDialog() == DialogResult.OK )
				_wfcontroller.WorkflowView.PerformLayout();
		}

		private void tsbtnPrint_Click(object sender, EventArgs e)
		{
			PrintDialog dlg = new PrintDialog();
			dlg.UseEXDialog = true;
			dlg.Document = _wfcontroller.WorkflowView.PrintDocument;
			if ( dlg.ShowDialog() == DialogResult.OK )
				_wfcontroller.WorkflowView.PrintDocument.Print();
		}

		private void tsmiSaveWFImgToClipboard_Click(object sender, EventArgs e)
		{
			this._wfcontroller.WorkflowView.SaveWorkflowImageToClipboard();
		}

		private void tsmiWFOptions_Click(object sender, EventArgs e)
		{
			FormWorkflowOptions frm = new FormWorkflowOptions(_wfcontroller.Workflow);
			frm.ShowDialog();
		}

		#endregion

		#region Tab Control

		private void tabCtrlWorkflow_SelectedIndexChanged(object sender, EventArgs e)
		{
		}

		private void tabCtrlWorkflow_Selected(object sender, TabControlEventArgs e)
		{
			showTab(tabCtrlWorkflow.SelectedTab);
		}
		private void tabCtrlWorkflow_Deselecting(object sender, TabControlCancelEventArgs e)
		{
			if ( e.Action == TabControlAction.Deselecting &&
				 e.TabPage != tabWorkflow && e.TabPage != tabBinding && e.TabPage != tabDeploy ) {
				saveTab(e.TabPage);
			}
		}

		#endregion

		#region Generate / Deploy
		private void btnSelectTargetFolder_Click(object sender, EventArgs e)
		{
			string path = txtTargetFolder.Text;
			if ( !string.IsNullOrEmpty(path) && Directory.Exists(path) ) {
				dlgSelectFolder.SelectedPath = path;
				if ( !dlgSelectFolder.SelectedPath.EndsWith("\\") )
					dlgSelectFolder.SelectedPath += "\\";
			}
			if ( dlgSelectFolder.ShowDialog() == DialogResult.OK ) {
				txtTargetFolder.Text = dlgSelectFolder.SelectedPath;
			}
		}

		private void btnUpdate_Click(object sender, EventArgs e)
		{
			doDeploy(true);
		}
		private void btnRegenerate_Click(object sender, EventArgs e)
		{
			doDeploy(false);
		}

		private void rbGenTypeConfig_CheckedChanged(object sender, EventArgs e)
		{
			//if ( rbGenTypeConfig.Checked ) {
			//    _wfcontroller.Workflow.ExtendedProperties.ConfigurationLevel =
			//        ConfigurationLevel.UtilizeConfiguration;
			//}
		}
		private void rbGenTypeCode_CheckedChanged(object sender, EventArgs e)
		{
			//if ( rbGenTypeCode.Checked ) {
			//    _wfcontroller.Workflow.ExtendedProperties.ConfigurationLevel =
			//        ConfigurationLevel.CompleteCodeGeneration;
			//}
		}

		#endregion

		#region Task List
		private void TaskListService_RefreshTaskList(object sender, EventArgs e)
		{
			doValidation();
		}
		private void tls_TaskItemAction(object sender, ITaskItemEventArgs e)
		{
			if ( e.TaskItem == null ) return;
			if ( e.TaskItem.SourceName == WorkflowValidatorSources.BusinessProcess ) {
				tabCtrlWorkflow.SelectedTab = tabWorkflow;
			} else if ( e.TaskItem.SourceName == WorkflowValidatorSources.FlowPolicy ) {
				tabCtrlWorkflow.SelectedTab = tabProcFlowPolicy;
			} else if ( e.TaskItem.SourceName == WorkflowValidatorSources.ParticipantPolicy ) {
				tabCtrlWorkflow.SelectedTab = tabParticipantPolicy;
			} else if ( e.TaskItem.SourceName == WorkflowValidatorSources.Subscriptions ) {
				tabCtrlWorkflow.SelectedTab = tabSubscriptions;
			} else if ( e.TaskItem.SourceName == WorkflowValidatorSources.Composite ) {
				tabCtrlWorkflow.SelectedTab = tabComposite;
			} else if ( e.TaskItem.SourceName == WorkflowValidatorSources.Binding ) {
				tabCtrlWorkflow.SelectedTab = tabBinding;
			} else if ( e.TaskItem.SourceName == WorkflowValidatorSources.Notifications ) {
				// TODO: open correct notifiaction!
				tabCtrlWorkflow.SelectedTab = tabWorkflow;
			} else if ( e.TaskItem.SourceName == WorkflowValidatorSources.WebServices ) {
				Helpers.ShowDetails(e.TaskItem.Tag as IRepositoryItem);
			}
		}
		private void wv_ValidationCompleted(object sender, EventArgs e)
		{
			IWorkflowValidator wv = sender as IWorkflowValidator;
			ITaskListService tls = _wfcontroller.GetService(typeof(ITaskListService)) as ITaskListService;
			while ( wv.IsBusy ) { }
			if ( tls != null && tls.GetViewItemCount(_wfcontroller.Workflow) < 8 ) {
				doValidation();
			}
			groupTasksErrors.Refresh();
		}

		#endregion

		void Repository_RepositoryChanged(object sender, RepositoryChangedEventArgs e)
		{
			if ( _wfcontroller == null ) return;
			if ( e.Member == null ) return;
			if ( e.RepositoryItem == _wfcontroller.Workflow ) {
				if ( e.Member.Name == "ExtendedProperties" ) {
				}
			}
		}

		private void closeToolStripMenuItem_Click(object sender, EventArgs e)
		{
			this.Close();
		}

		private void closeAllButThisToolStripMenuItem_Click(object sender, EventArgs e)
		{
			Helpers.CloseAllWindows(this.DockPanel, this);
		}

		private void closeAllToolStripMenuItem_Click(object sender, EventArgs e)
		{
			Helpers.CloseAllWindows(this.DockPanel);
		}
		#endregion

		#endregion

		#region Private Class: WFBuildTypeItem
		private class WFBuildTypeItem
		{
			public WFBuildTypeItem(WorkflowBuildType type)
			{
				BuildType = type;
			}
			public WorkflowBuildType BuildType;
			public override int GetHashCode()
			{
				return BuildType.GetHashCode();
			}
			public override bool Equals(object obj)
			{
				if ( obj is WorkflowBuildType )
					return BuildType == (WorkflowBuildType)obj;
				else
					return base.Equals(obj);
			}
			public override string ToString()
			{
				FieldInfo fi = typeof(WorkflowBuildType).GetField(BuildType.ToString());
				object[] descAtts = fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
				if ( descAtts.Length > 0 ) {
					return ( (DescriptionAttribute)descAtts[0] ).Description;
				} else {
					return BuildType.ToString();
				}
			}
		}
		#endregion

		private void btnDeployOptions_Click(object sender, EventArgs e)
		{
			FormWorkflowOptions frm = new FormWorkflowOptions(_wfcontroller.Workflow, true);
			frm.ShowDialog();
		}

	}

}
